import {Injectable} from '@angular/core';
import {SessionStorageService} from '@core/storage/storage.module';
import {NHttpClinet} from '@core/utils/http.client';

@Injectable()
export class LoginService {
  constructor(private _storage: SessionStorageService, private http: NHttpClinet) {
  }

  login(username: string, password: string) {
    return new Promise((resolve, reject) => {
      this.http.post(`${this.http.SERVER_URL}identification`, {username: username, password: password})
        .subscribe((response) => {
          if (response.result === '00000000') {
            this._storage.set('username', username);
            this._storage.set('token', response.data.token);
            resolve(response.data);
          } else {
            reject(response.data);
          }
        });
    });
  }

  signOut() {
    return new Promise((resolve, reject) => {
      this.http.delete(`${this.http.SERVER_URL}identification`)
        .subscribe((response) => {
          if (response.result === '00000000') {
            this._storage.clear();
            resolve(response.data);
          } else {
            reject(response.data);
          }
        });
    });
  }
}
